package com.azh.server.datam.logger;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import com.azh.server.tx.TxManagerImpl;
import com.azh.server.util.ExceptionUtils;
import com.azh.server.util.FileCommonUtils;
import com.azh.server.util.Parser;

/**
 * @author zhaozhenhang <zhaozhenhang@kuaishou.com>
 * Created on 2022-04-25
 */
public interface Logger {

    public void log(byte[] data);

    public void truncate(long x) throws Exception;

    public byte[] next();

    public void rewind();

    public void close();

    public static Logger create(String path) {
        File file = new File(path + LoggerImpl.log_suffix);
        try {
            if (!file.createNewFile()) {
                ExceptionUtils.getMessage(new RuntimeException("File already exists!"));
            }
        } catch (Exception e) {
            ExceptionUtils.getMessage(e);
        }
        if (FileCommonUtils.canReadOrWrite(file)) {
            ExceptionUtils.getMessage(new RuntimeException("File cannot read or write!"));
        }
        FileChannel channel = null;
        RandomAccessFile refFile = null;
        try {
            refFile = new RandomAccessFile(file, "rw");
            channel = refFile.getChannel();
        } catch (FileNotFoundException e) {
            ExceptionUtils.getMessage(e);
        }
        ByteBuffer buffer = ByteBuffer.wrap(Parser.intToByte(0));
        try {
            channel.position(0);
            channel.write(buffer);
            channel.force(false);
        } catch (IOException e) {
            ExceptionUtils.getMessage(e);
        }
        return new LoggerImpl(refFile, channel, 0);
    }

    public static Logger open(String path) {
        File file = new File(path + LoggerImpl.log_suffix);
        if (!file.exists()) {
            ExceptionUtils.getMessage(new FileNotFoundException("对应的tx文件不存在"));
        }
        if (FileCommonUtils.canReadOrWrite(file)) {
            ExceptionUtils.getMessage(new Exception("文件无法读写，可能是因为没有权限或者其他原因..."));
        }
        FileChannel channel = null;
        RandomAccessFile refFile = null;
        try {
            refFile = new RandomAccessFile(file, "rw");
            channel = refFile.getChannel();
        } catch (FileNotFoundException e) {
            ExceptionUtils.getMessage(e);
        }
        LoggerImpl logger = new LoggerImpl(refFile, channel);
        logger.init();
        return logger;
    }


}
